package com.yunji.hushuang.framework.web.servlet;

import com.yunji.hushuang.framework.stereotype.HsAutowired;
import com.yunji.hushuang.framework.stereotype.HsComponent;
import com.yunji.hushuang.framework.stereotype.HsController;
import com.yunji.hushuang.framework.web.annotation.HsRequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author hushuang
 * @since 2019/11/22
 */
public class HsDispatcherServlet extends HttpServlet {

    private static final String CONTEXT_CONFIG_LOCATION = "contextConfigLocation";

    private static final String CLASS_PATH_STRING = "classpath:";

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>();

    private Map<String, Object> ioc = new HashMap<>();

    private List<HandlerMapping> mappings = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doDispatch(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doDispatch(req, resp);
    }

    protected void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        // 匹配映射关系
        HandlerMapping mapping = getHandlerMapping(req);
        if (mapping == null) {
            resp.getWriter().write("404 Not Found");
            return;
        }

        Object[] params = new Object[mapping.getParameterCount()];

        for (Map.Entry<String, Integer> entry : mapping.getParamIndexMapping().entrySet()) {
            String value = req.getParameter(entry.getKey());
            params[entry.getValue()] = convert(mapping.getParameterType(entry.getValue()), value);
        }

        int reqIndex = mapping.getParameterIndex(HttpServletRequest.class.getName());
        if (reqIndex >= 0) {
            params[reqIndex] = req;
        }

        int respIndex = mapping.getParameterIndex(HttpServletResponse.class.getName());
        if (respIndex >= 0) {
            params[respIndex] = resp;
        }

        try {
            Object result = mapping.process(params);
            if (result != null) {
                resp.getWriter().write(result.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Object convert(Class<?> parameterType, String value) {
        if (parameterType == Integer.class) {
            return Integer.valueOf(value);
        } else if (parameterType == Double.class) {
            return Double.valueOf(value);
        }
        return value;
    }

    @Override
    public void init() throws ServletException {
        System.out.println("init framework starting");
        // 加载配置
        doLoadConfig();
        // 扫描类
        doScan();
        // 实例化，并装入 IOC 容器
        doInstance();
        // 依赖注入
        doAutowired();
        // 初始化 HandlerMapping
        initHandlerMapping();
        // 启动完成
        System.out.println("init framework finished");
    }

    private HandlerMapping getHandlerMapping(HttpServletRequest req) {
        if (mappings.isEmpty()) {
            return null;
        }

        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");

        for (HandlerMapping mapping : mappings) {
            if (mapping.isMatches(url)) {
                return mapping;
            }
        }
        return null;
    }

    private void initHandlerMapping() {
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            HsController controller = clazz.getAnnotation(HsController.class);
            if (controller == null) {
                continue;
            }

            String basePath = "/";
            HsRequestMapping requestMapping = clazz.getAnnotation(HsRequestMapping.class);
            if (requestMapping != null) {
                basePath += requestMapping.value();
            }

            for (Method method : clazz.getMethods()) {
                requestMapping = method.getAnnotation(HsRequestMapping.class);
                if (requestMapping != null) {
                    String requestPath = (basePath + requestMapping.value().trim()).replaceAll("/+", "/");
                    Pattern pattern = Pattern.compile(requestPath);
                    // 提取出参数顺序
                    mappings.add(new HandlerMapping(pattern, entry.getValue(), method));
                }
            }
        }
        System.out.println("init handler mapping finished");
    }

    private void doAutowired() {
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            for (Field field : entry.getValue().getClass().getDeclaredFields()) {
                HsAutowired autowired = field.getAnnotation(HsAutowired.class);
                if (autowired == null) {
                    continue;
                }
                String name = autowired.value().trim();
                if (name.isEmpty()) {
                    // 通过类型生成名字
                    name = field.getType().getName();
                }
                Object instance = ioc.get(name);
                if (instance == null) {
                    throw new NullPointerException(String.format("找不到 %s 的 %s 的实例", entry.getValue().getClass(), field.getName()));
                }
                // 给 Field 设值
                try {
                    field.setAccessible(true);
                    field.set(entry.getValue(), instance);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("init autowired finished");
    }

    private void doInstance() {
        try {
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(HsController.class)) {
                    ioc.put(lowerFirst(clazz.getSimpleName()), clazz.newInstance());
                } else if (clazz.isAnnotationPresent(HsComponent.class)) {
                    HsComponent component = clazz.getAnnotation(HsComponent.class);

                    String name = component.value().trim();
                    Object instance = clazz.newInstance();
                    // 如果没设置名字，就用类型生成实例
                    if (name.isEmpty()) {
                        ioc.put(clazz.getName(), instance);
                        for (Class<?> type : clazz.getInterfaces()) {
                            ioc.put(type.getName(), instance);
                        }
                    } else {
                        ioc.put(name, instance);
                    }
                }
            }
            System.out.println("init ioc finished. size=" + ioc.size());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void doScan() {
        doScan(properties.getProperty("scan-package").trim());
    }

    private void doScan(String packagePath) {
        URL url = getClass().getClassLoader().getResource("/" + packagePath.replaceAll("\\.", "\\/"));
        if (url == null) {
            return;
        }

        File file = new File(url.getFile());
        File[] files = file.listFiles();
        if (files == null) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                doScan(packagePath + "." + f.getName());
            } else {
                classNames.add(packagePath + "." + f.getName().replace(".class", "").trim());
            }
        }
    }

    private void doLoadConfig() {
        String contextConfigLocation = getInitParameter(CONTEXT_CONFIG_LOCATION);
        if (contextConfigLocation.toLowerCase().startsWith(CLASS_PATH_STRING)) {
            contextConfigLocation = contextConfigLocation.substring(CLASS_PATH_STRING.length());
        }
        try (InputStream in = getClass().getClassLoader().getResourceAsStream(contextConfigLocation)) {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private String lowerFirst(String string) {
        char[] chars = string.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }
}
